package org.egomsl.mw.region;

import org.apache.hadoop.fs.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

public class RegionUtils {
    public static List<FileMeta> getSegmentFiles(FileSystem fs, Path regionDir) throws IOException {
        ArrayList<FileMeta> storefiles = new ArrayList<>();

        RemoteIterator<LocatedFileStatus> iter =
                fs.listFiles(regionDir, false);

        while(iter.hasNext()) {
            FileStatus status = iter.next();
            Path file = status.getPath();

            if(Pattern.matches(RegionConstants.reversedBlockFilePattern, file.getName())
                    || Pattern.matches(RegionConstants.sequentialBlockFilePattern, file.getName())) {

                String[] fields = file.getName().split("[-.]");
                assert fields.length == 3;

                int seqNum = Integer.valueOf(fields[1]);

                boolean reversed = false;
                if("seq".equals(fields[2])) {
                    reversed = false;
                }

                storefiles.add(new FileMeta(status, seqNum, reversed));
            }
        }

        Collections.sort(storefiles);
        Collections.reverse(storefiles);

        return storefiles;
    }
}
